<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="班级名称">
      <el-input v-model="form.class_name" />
    </el-form-item>
    <el-form-item label="所属专业">
      <el-select v-model="form.major_id" @change="getMajorInfo">
        <el-option 
          v-for="major in majors" 
          :key="major.major_id" 
          :label="major.major_name" 
          :value="major.major_id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="所属学院">
      <el-input v-model="form.department_name" disabled/>
    </el-form-item>
    <el-form-item label="年级">
      <el-input v-model="form.grade" />
    </el-form-item>
    <el-form-item label="学生人数">
      <el-input v-model="form.student_count" disabled/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">确认添加</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import ClassApi from '@/api/ClassApi';

export default {
  data() {
    return {
      form: {
        class_name: '',
        major_id: '',
        department_name: '',
        grade: '',
        student_count: 0
      },
      majors: [] // 专业数据
    };
  },
  methods: {
    submitForm() {
      // 确保表单数据完整
      if (!this.form.class_name || !this.form.major_id || !this.form.grade) {
        this.$message.error('请填写完整信息');
        return;
      }
      
      // 触发提交事件
      this.$emit('submit-form', this.form);
    },
    closeDialog() {
      this.$emit('close-dialog');
    },
    getMajorInfo(major_id) {
      const selectedMajor = this.majors.find(m => m.major_id === major_id);
      if (selectedMajor) {
        this.form.department_name = selectedMajor.department_name;
        this.form.major_id = selectedMajor.major_id; 
        this.form.department_id=selectedMajor.department_id;
      }
    },
    fetchMajors() {
      try {
        ClassApi.getMajorsForm().then(res => {
          if (res.data.code === 200) {
            this.majors = res.data.data ||res.data;
          } else {
            this.$message.error('获取专业信息失败');
          }
        });
      } catch (error) {
        console.error("专业信息获取错误:", error);
        this.$message.error('获取专业信息失败');
      }
    }
  },
  created() {
    this.fetchMajors();
  }
};
</script>
